package example.servlets;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Collection;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;

import example.AppConstants;
import example.model.Customer;

/**
 * Servlet implementation class CustomersServlet
 */
public class CustomersServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CustomersServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
    @SuppressWarnings("all")
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String uri = request.getRequestURI();
		//obtain customers object from servlet context
		Collection<Customer> customersResult = (Collection<Customer>)getServletContext().getAttribute(AppConstants.CUSTOMERS);
		
		if (uri.indexOf(AppConstants.NAME) != -1){//filter customer by specific name
			String name = uri.substring(uri.indexOf(AppConstants.NAME) + AppConstants.NAME.length() + 1);
			name = name.replaceAll("\\%20", " ");
			Collection<Customer> temp = new ArrayList<Customer>();
			for (Customer customer : customersResult){
				if (customer.getName().equals(name)){
					temp.add(customer);
				}
			}
			
			customersResult = temp;
		}
		
		Gson gson = new Gson();
		//convert from customers collection to json
		String customerJsonResult = gson.toJson(customersResult, AppConstants.CUSTOMER_COLLECTION);
		
		PrintWriter writer = response.getWriter();
		writer.println(customerJsonResult);
		writer.close();
		
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

}
